package cn.hloger.spider.demo.proxyDemo.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器 - 代理请求的
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/4/2
 */
@Component
public class ZhyReqInterceptor implements HandlerInterceptor {
    /**
     * 代理项目名称
     */
    @Value("${proxy.url.flag:false}")
    private boolean proxyUrlFLag;

    private Map<String, String> proxyPathMap = new HashMap<>();

    public Map<String, String> getProxyPathMap() {
        return this.proxyPathMap;
    }

    public void putProxyPathMap(String key, String value) {
        this.proxyPathMap.put(key, value);
    }

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 请求处理之后进行拦截处理
        if (!proxyUrlFLag) {
            return true;
        }
        String servletPath = request.getServletPath();
        if (CollectionUtil.isNotEmpty(proxyPathMap) &&
                proxyPathMap.keySet().stream().anyMatch(pattern -> pathMatcher.match(pattern, servletPath))) {
            String proxyUrl = proxyPathMap.get(request.getServletPath());
            RequestDispatcher rd = request.getRequestDispatcher(proxyUrl);
            //避免/xx/**路劲转发错误, 如果没有找到可以转发的对象就不转发了
            if (rd != null) {
                // 转发请求到其他Controller
                rd.forward(request, response);
                // 停止后续处理
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // 请求完成后进行拦截处理
    }
}
